// pages/rank/rank.ts
import { examTypes } from '../math/math'
import { formatTime } from '../../utils/util'
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    scores: [] as any,
    examTypes,
    typeIndex: 0,
    testTimes: ['1分钟', '5分钟','10分钟','15分钟'],
    timeIndex: 1,
    currentPage: 1,
    total: 0
  },
  loadMore() {
    if (this.data.scores.length === this.data.total) {
      return
    }
    this.setData({ currentPage: this.data.currentPage + 1 })
    this.getData().then((data: any) => {
      this.setData({ scores: [...this.data.scores, ...data] })
    })
  },
  changeTestType(val: any) {
    this.setData({ typeIndex: Number(val.detail.value), currentPage: 1 })
    this.getData().then(data => {
      this.setData({ scores: data })
    })
  },
  changeTime(val: any) {
    this.setData({ timeIndex: Number(val.detail.value), currentPage: 1 })
    this.getData().then(data => {
      this.setData({ scores: data })
    })
  },
  getData() {
    return new Promise((resolve, reject) => {
      const that = this
      const mid = {
        prop: 'rightNum',
        order: 'desc',
        pageSize: 50,
        currentPage: this.data.currentPage,
        type: this.data.examTypes[this.data.typeIndex],
        testMinute: this.data.testTimes[this.data.timeIndex].replace('分钟','')
      }
      wx.request({
        header: {
          Authorization: app.globalData.userInfo.token
        },
        url: `https://www.liqiantw.icu:3000/score/rankList`,
        method: 'POST',
        data: mid,
        success: function ({ data: { data, total } }: any) {
          data.forEach((item: any) => {
            const { date, avatar, nickName, name } = item
            item.date = formatTime(new Date(date))
            if (!avatar && !nickName) {
              item.name = name.slice(0, 2) + '***' + name.slice(-2)
            }
          })
          that.setData({ total: total })
          resolve(data)
        },
        fail: function () {
          reject([])
        }
      });
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({ currentPage: 1 })
    this.getData().then(data => {
      this.setData({ scores: data })
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})